package cn.fl.insurance.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.insurance.condition.InsPlcTypDtlQueryCondition;
import cn.fl.insurance.condition.InsTypInfoQueryCondition;
import cn.fl.insurance.service.IInsPlcTypDtlService;
import cn.fl.insurance.service.IInsTypInfoService;
import cn.fl.insurance.vo.InsPlcTypDtlVO;
import cn.fl.insurance.vo.InsTypInfoVO;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 保单险种明细 控制层
 */
@Controller
@RequestMapping("/insurance/insPlcTypDtl")
public class InsPlcTypDtlController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InsPlcTypDtlController.class);

    /**
     * InsPlcTypDtl 服务层BEAN
     */
    @Autowired
    private IInsPlcTypDtlService insPlcTypDtlService;

    /**
     * 数据字典 服务层BEAN
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    
    /**
     * InsTypInfo 服务层BEAN
     */
    @Autowired
    private IInsTypInfoService insTypInfoService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载InsPlcTypDtl列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insPlcTypDtl/insPlcTypDtlList");
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载InsPlcTypDtl Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insPlcTypDtl/insPlcTypDtlModify");
        //TODO 加载数据字典数据、传值等 ？

        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载InsPlcTypDtl Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("insurance/insPlcTypDtl/insPlcTypDtlModify");
        //TODO 加载数据字典数据、传值等 ？

        String id = request.getParameter("id");
        InsPlcTypDtlVO insPlcTypDtlVO = this.insPlcTypDtlService.selectById(Long.valueOf(id));
        mav.addObject("insPlcTypDtlVO", insPlcTypDtlVO);
        return mav;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initInsPlcTypDtlList(HttpServletRequest request, HttpServletResponse response) {
    	List<InsPlcTypDtlVO> list = null;
        String insPlcId = request.getParameter("insPlcId");
        if (StringUtils.isNotBlank(insPlcId)) {
        	//根据保单查询保单险种
            InsPlcTypDtlQueryCondition qc = new InsPlcTypDtlQueryCondition();
            qc.setInsPlcId(Long.valueOf(insPlcId));
            String dtlTypCd=request.getParameter("dtlTypCd");
            if(StringUtils.isBlank(dtlTypCd)){
                qc.setDtlTypCd("1");
            }else{
                qc.setDtlTypCd(dtlTypCd);
            }
            String apprId=request.getParameter("apprId");
            if(StringUtils.isNotBlank(apprId)){
                qc.setApprId(Long.valueOf(apprId));
            }
            list = insPlcTypDtlService.searchList(qc);
            for(InsPlcTypDtlVO vo : list){
                vo.setInsAmtDb(Double.valueOf(vo.getInsAmt().toString())/100);
                vo.setInsFeeDb(Double.valueOf(vo.getInsFee().toString())/100);
            }
            BaseLogUtils.info(logger, "initInsTypInfoList", "初始化InsTypInfo列表页面数据.DATA: {insPlcId：" + insPlcId + "}", CurrentThreadContext.getCurrentUserName());
        } else {
        	//根据保险种类查询险种
            InsTypInfoQueryCondition qc = new InsTypInfoQueryCondition();
            String insTypCd = request.getParameter("insTypCd");
            if (StringUtils.isNotEmpty(insTypCd)) {
                //qc.setInsTypCd(insTypCd.trim());
                qc.setTypPid(Long.valueOf(insTypCd));
            } else {
                return null;
            }

            String isDefVi = request.getParameter("isDefVi");
            if (StringUtils.isNotEmpty(isDefVi)) {
                qc.setIsDefVi(Integer.valueOf(isDefVi));
            }
            List<InsTypInfoVO> typList = this.insTypInfoService.searchList(qc);
            list = new ArrayList<>();
            InsPlcTypDtlVO dtlVO;
            for (InsTypInfoVO vo : typList) {
                dtlVO = new InsPlcTypDtlVO();
                dtlVO.setInsTypId(vo.getId());
                dtlVO.setInsTypNm(vo.getTypNm());
                dtlVO.setDtlTypCd("1");//险种明细类型1.保单2.批单
                dtlVO.setIsNonDedu(0);//不计免赔 1.是
                dtlVO.setInsFeeDb(0.00);//保费金额
                dtlVO.setInsAmtDb(0.00);//保险金额
                dtlVO.setTypClsCd(vo.getTypClsCd());//是否必保险种 1.必保 2.选保
                list.add(dtlVO);
            }
            BaseLogUtils.info(logger, "initInsTypInfoList", "初始化InsTypInfo列表页面数据.DATA:{insTypCd:" + insTypCd + "}", CurrentThreadContext.getCurrentUserName());
        }
        ListPageVO<InsPlcTypDtlVO> listPage = new ListPageVO<>(list, list.size());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeInsPlcTypDtlByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeInsPlcTypDtlByIds", "删除InsPlcTypDtl数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            boolean success = this.insPlcTypDtlService.removeByIds(idsList);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeInsPlcTypDtlByIds", "删除InsPlcTypDtl数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeInsPlcTypDtlByIds", "删除InsPlcTypDtl数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeInsPlcTypDtlByIds", "删除InsPlcTypDtl数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeInsPlcTypDtlByIds", "删除InsPlcTypDtl数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getInsPlcTypDtlById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getInsPlcTypDtlById", "获取InsPlcTypDtl数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            InsPlcTypDtlVO vo = this.insPlcTypDtlService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getInsPlcTypDtlById", "获取InsPlcTypDtl数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getInsPlcTypDtlById", "获取InsPlcTypDtl数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getInsPlcTypDtlById", "获取InsPlcTypDtl数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getInsPlcTypDtlById", "获取InsPlcTypDtl数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addInsPlcTypDtl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        InsPlcTypDtlVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForInsPlcTypDtl(request);//获取参数
            Long id = this.insPlcTypDtlService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "addInsPlcTypDtl", "新增InsPlcTypDtl数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addInsPlcTypDtl", "新增InsPlcTypDtl数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addInsPlcTypDtl", "新增InsPlcTypDtl数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyInsPlcTypDtl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        InsPlcTypDtlVO entity = null;
        try {
            entity = this.getRequestParamForInsPlcTypDtl(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyInsPlcTypDtl", "修改InsPlcTypDtl信息,主键参数为空！.ID:" + entity.getId(), CurrentThreadContext.getCurrentUserName());
                return result;
            }

            boolean success = this.insPlcTypDtlService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyInsPlcTypDtl", "修改InsPlcTypDtl数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyInsPlcTypDtl", "修改InsPlcTypDtl数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyInsPlcTypDtl", "修改InsPlcTypDtl数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyInsPlcTypDtl", "修改InsPlcTypDtl数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private InsPlcTypDtlVO getRequestParamForInsPlcTypDtl(HttpServletRequest request) throws BaseException {
        //TODO 获取参数
        String id = request.getParameter("id");//主键
        String insPlcId = request.getParameter("insPlcId");
        String insTypId = request.getParameter("insTypId");
        String insTypNm = request.getParameter("insTypNm");
        String insAmt = request.getParameter("insAmt");
        String insFee = request.getParameter("insFee");
        String nonDeduAmt = request.getParameter("nonDeduAmt");
        String plcTypRem = request.getParameter("plcTypRem");
        String dtlTyp = request.getParameter("dtlTyp");
        String apprId = request.getParameter("apprId");


        //TODO 验证参数并赋值
        InsPlcTypDtlVO entity = new InsPlcTypDtlVO();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
        }

//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }
//      entity.setX();

        Date tm = new Date();
        entity.setCrtTm(tm);
        entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        entity.setMdfTm(tm);
        entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        return entity;
    }
}

